using Microsoft.AspNetCore.Mvc;
using SupplierCustomerManagement.Read.API.Dtos;
using SupplierCustomerManagement.Read.API.Dtos.Inventory;
using SupplierCustomerManagement.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace SupplierCustomerManagement.Read.API.Controllers
{
    /// <summary>
    /// 实时存栏相关接口
    /// </summary>
    [ApiController]
    [Route("api/inventory")]
    public class InventoryController : ControllerBase
    {
        private readonly SupplierDbContext _db;
        private readonly ILogger<InventoryController> _logger;

        public InventoryController(SupplierDbContext db, ILogger<InventoryController> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 获取实时总存栏
        /// </summary>
        [HttpGet("realtime-summary")]
        public async Task<ActionResult<ApiResponse<RealtimeTotalSummaryDto>>> GetRealtimeSummary([FromQuery] string? date, [FromQuery] int? farmId)
        {
            try
            {
                // 口径：Sheep 表中 CurrentStatus 为 "存栏" 的数量（可选按 farmId 过滤）
                var query = _db.Sheeps.AsNoTracking().AsQueryable();
                if (farmId.HasValue)
                    query = query.Where(s => s.FarmId == farmId.Value);

                // 这里可扩展基于 date 的历史口径（需要历史表），当前按现势口径统计
                var total = await query.CountAsync();
                var dto = new RealtimeTotalSummaryDto { totalCount = total };
                return Ok(ApiResponse<RealtimeTotalSummaryDto>.Ok(dto));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取实时总存栏失败");
                return StatusCode(500, ApiResponse<RealtimeTotalSummaryDto>.Fail($"获取实时总存栏失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取种母存栏分布（哺乳/妊娠/空怀 等）
        /// </summary>
        [HttpGet("ewe-distribution")]
        public async Task<ActionResult<ApiResponse<EweDistributionDto>>> GetEweDistribution([FromQuery] string? date, [FromQuery] int? farmId)
        {
            try
            {
                // 口径：Sheep 表中 Gender=母，且处于存栏，聚合繁殖状态（若有更细的 EweReproductiveStatus 可替换）
                var query = _db.Sheeps.AsNoTracking().Where(s => s.Gender == "母");
                if (farmId.HasValue)
                    query = query.Where(s => s.FarmId == farmId.Value);

                // 暂以 Sheep.CurrentStatus 作为分组字段的示例（如果有更合适的字段请替换）
                var grouped = await query
                    .GroupBy(s => s.CurrentStatus)
                    .Select(g => new { Name = g.Key, Value = g.Count() })
                    .ToListAsync();

                // 映射配色建议（种母繁殖状态统一调色板）
                var colorMap = new Dictionary<string, string>
                {
                    ["哺乳"] = "#FF9F7F",
                    ["妊娠"] = "#FF7F7F",
                    ["空怀"] = "#FFC069",
                    ["淘汰"] = "#FFB6B9",
                    ["存栏"] = "#F7B267",
                    ["待产"] = "#F6BD60",
                    ["断奶"] = "#FAD7A0",
                    ["后备"] = "#F9E79F"
                };

                var dto = new EweDistributionDto
                {
                    items = grouped.Select(x => new EweDistributionItemDto
                    {
                        name = x.Name,
                        value = x.Value,
                        color = colorMap.ContainsKey(x.Name) ? colorMap[x.Name] : null
                    }).ToList()
                };

                return Ok(ApiResponse<EweDistributionDto>.Ok(dto));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取种母存栏分布失败");
                return StatusCode(500, ApiResponse<EweDistributionDto>.Fail($"获取种母存栏分布失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取种公存栏品种结构
        /// </summary>
        [HttpGet("ram-breed-distribution")]
        public async Task<ActionResult<ApiResponse<RamBreedDistributionDto>>> GetRamBreedDistribution([FromQuery] string? date, [FromQuery] int? farmId)
        {
            try
            {
                // 口径：Sheep 表中 Gender=公，按 Breed 分组统计（可选按 farm 过滤）
                var query = _db.Sheeps.AsNoTracking().Where(s => s.Gender == "公");
                if (farmId.HasValue)
                    query = query.Where(s => s.FarmId == farmId.Value);

                var grouped = await query
                    .GroupBy(s => s.Breed)
                    .Select(g => new { Name = g.Key, Value = g.Count() })
                    .ToListAsync();

                // 配色建议（固定调色板，便于前端图例稳定展示）
                var colorMap = new Dictionary<string, string>
                {
                    ["青青草原品种"] = "#409EFF",
                    ["湖羊"] = "#67C23A",
                    ["萨福克羊"] = "#E6A23C",
                    ["杜湖"] = "#F56C6C",
                    ["澳湖"] = "#909399",
                    ["小尾寒羊"] = "#9B59B6",
                    ["夏洛莱羊"] = "#1ABC9C",
                    ["波尔山羊"] = "#E74C3C",
                    ["黑山羊"] = "#34495E",
                    ["东弗里斯兰"] = "#00B894",
                    ["德国美利奴"] = "#2D98DA",
                    ["科里代尔"] = "#F39C12"
                };

                var dto = new RamBreedDistributionDto
                {
                    items = grouped.Select(x => new RamBreedItemDto
                    {
                        name = x.Name,
                        value = x.Value,
                        color = colorMap.ContainsKey(x.Name) ? colorMap[x.Name] : null
                    }).ToList()
                };

                return Ok(ApiResponse<RamBreedDistributionDto>.Ok(dto));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取种公存栏品种结构失败");
                return StatusCode(500, ApiResponse<RamBreedDistributionDto>.Fail($"获取种公存栏品种结构失败: {ex.Message}"));
            }
        }
    }
}
